// 分类模块
import { topCategory } from '@/api/constant.js'
import { findAllCategory } from '@/api/category.js'
export default {
  namespaced: true,
  state() {
    return {
      // 分类信息集合
      // 返回一个新的数组
      list: topCategory.map(item => ({ name: item }))
    }
  },
  // 请求成功是payload获取分类的数组
  mutations: {
    setCategory(state, payload) {
      state.list = payload
    },
    // 定义show和hide函数，控制当前分类的隐藏和显示
    show(state, id) {
      const currCategory = state.list.find(item => item.id === id)
      currCategory.open = true
    },
    hide(state, id) {
      const currCategory = state.list.find(item => item.id === id)
      currCategory.open = false
    }
  },
  actions: {
    async getCategory({ commit }) {
      // 请求分类数据
      const { result } = await findAllCategory()
      // 给每个分类加上二级分类显示隐藏的是数据
      result.forEach(element => {
        element.open = false
      })
      commit('setCategory', result)
    }
  }
}
